﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime;
using com.sap.mw.jco;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Data;

namespace SSISForSAPComponents
{
    [
        DtsPipelineComponent
        (
            DisplayName = "SAP Source",
            ComponentType = ComponentType.SourceAdapter,
            UITypeName = "SSISForSAPComponents.SAPDataSourceEditGUi,SSISForSAPComponents2008, Version=2.0.0.0, Culture=neutral, PublicKeyToken=440628c79e3678cd"
            , IconResource = "SSISForSAPComponents.DataSource.ico"
        )
    ]
    public class SAPDataSource : PipelineComponent
    {

        private Hashtable HashProcessedInputs = new System.Collections.Hashtable();
        private com.sap.mw.jco.JCO.Client conn;
        private com.sap.mw.jco.JCO.Repository repostory;
        private System.Collections.Generic.Dictionary<string, com.sap.mw.jco.JCO.Table> PipelineInputTables = new Dictionary<string, JCO.Table>();
        private List<DataTable> PipelineTableMapings = new List<DataTable>();
        private List<TableType> ImportTableType = new List<TableType>();
        private PipelineBuffer[] outbuffers;

        //private IDTSOutput90[] outs;

        #region 设计时

        /// <summary>
        /// 设置组件属性
        /// </summary>
        public override void ProvideComponentProperties()
        {
            // 重设组件属性
            ComponentMetaData.RuntimeConnectionCollection.RemoveAll();
            RemoveAllInputsOutputsAndCustomProperties();

            // 添加自定义属性
            IDTSCustomProperty100 rfc = ComponentMetaData.CustomPropertyCollection.New();
            rfc.Name = "rfcMame";
            rfc.Value = "";
            //添加连接
            IDTSRuntimeConnection100 connection = base.ComponentMetaData.RuntimeConnectionCollection.New();
            connection.Name = "SAP Connection";
            connection.Description = "SAP Connection";

            //添加TABLE输入类型
            IDTSCustomProperty100 importTableValue = ComponentMetaData.CustomPropertyCollection.New();
            importTableValue.Name = "ImportTableType";
            importTableValue.Value = "";
            //importTableValue.Value =  new System.Collections.Generic.Dictionary<string,string>();

            //添加TABLE输出类型
            IDTSCustomProperty100 OutTableValue = ComponentMetaData.CustomPropertyCollection.New();
            OutTableValue.Name = "OuterTableType";
            OutTableValue.Value = "";
            //OutTableValue.Value = new System.Collections.Generic.Dictionary<string, string>(); 

            //添加静态输入TABLE映射
            IDTSCustomProperty100 StaticTableValue = ComponentMetaData.CustomPropertyCollection.New();
            StaticTableValue.Name = "StaticTableValue";
            StaticTableValue.Value = "";

            //输入管道映射
            IDTSCustomProperty100 PipelineTableValue = ComponentMetaData.CustomPropertyCollection.New();
            PipelineTableValue.Name = "PipelineTableValue";
            PipelineTableValue.Value = "";


            //输入参数映射
            IDTSCustomProperty100 ImportParameterValue = ComponentMetaData.CustomPropertyCollection.New();
            ImportParameterValue.Name = "ImportParameterValue";
            ImportParameterValue.Value = "";

            //输出参数映射
            IDTSCustomProperty100 ExportParameterValue = ComponentMetaData.CustomPropertyCollection.New();
            ExportParameterValue.Name = "ExportParameterValue";
            ExportParameterValue.Value = "";
            //StaticTableValue.Value = new List<System.Data.DataTable>();

            // StaticTableValue.UITypeEditor = typeof(StaticTableMapingEditUI).AssemblyQualifiedName; 

        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        public override DTSValidationStatus Validate()
        {
            return 0;
        }
        /// <summary>
        /// 得到连接
        /// </summary>
        /// <param name="transaction"></param>
        public override void AcquireConnections(object transaction)
        {
            try
            {
                if (base.ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager != null)
                {
                    SAPConnectionManager manager = base.ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager.AcquireConnection(null) as SAPConnectionManager;
                    if (manager != null)
                    {
                        this.conn = com.sap.mw.jco.JCO.createClient(manager.CLIENT, manager.USER, manager.PASSWD, manager.Lang, manager.ASHOST, manager.SYSNR);
                        repostory = new com.sap.mw.jco.JCO.Repository("VSoft", this.conn);


                    }
                }
                else
                {

                    this.conn = null;
                }
            }
            catch (Exception ex)
            {
                this.FireError(ex.Message, true);

            }
        }
        /// <summary>
        /// 释放连接
        /// </summary>
        public override void ReleaseConnections()
        {
            this.conn = null;
        }
        public override void OnInputPathAttached(int inputID)
        {
            IDTSInput100 input = ComponentMetaData.InputCollection.GetObjectByID(inputID);

            IDTSVirtualInput100 vInput = input.GetVirtualInput();

            foreach (IDTSVirtualInputColumn100 vCol in vInput.VirtualInputColumnCollection)
                this.SetUsageType(inputID, vInput, vCol.LineageID, DTSUsageType.UT_READONLY);
        }

        /// <summary>
        /// 重设输出列
        /// </summary>
        public override void ReinitializeMetaData()
        {
            List<TableType> outputTableType = new List<TableType>();
            if (this.ComponentMetaData.CustomPropertyCollection["OuterTableType"].Value != null)
            {
                string xml = this.ComponentMetaData.CustomPropertyCollection["OuterTableType"].Value.ToString();
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<TableType>));
                System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                if (ms.Length > 0)
                {

                    outputTableType = ser.Deserialize(ms) as List<TableType>;
                }
            }
            List<TableType> inputTableType = new List<TableType>();
            if (this.ComponentMetaData.CustomPropertyCollection["ImportTableType"].Value != null)
            {
                string xml = this.ComponentMetaData.CustomPropertyCollection["ImportTableType"].Value.ToString();
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<TableType>));
                System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                if (ms.Length > 0)
                {

                    inputTableType = ser.Deserialize(ms) as List<TableType>;
                }
            }
            CreateMetadata(this.ComponentMetaData, outputTableType, conn, inputTableType);


        }
        public static void StaticReinitializeMetaData(IDTSComponentMetaData100 metadat90, List<TableType> outputTableType, com.sap.mw.jco.JCO.Client conn, List<TableType> inputTableType)
        {

            try
            {
                CreateMetadata(metadat90, outputTableType, conn, inputTableType);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private static void CreateMetadata(IDTSComponentMetaData100 metadat90, List<TableType> outputTableType, com.sap.mw.jco.JCO.Client conn, List<TableType> inputTableType)
        {

            //metadat90.OutputCollection.RemoveAll();
            conn.connect();
            com.sap.mw.jco.JCO.Repository repostory = new com.sap.mw.jco.JCO.Repository("VSoft", conn);

            com.sap.mw.jco.IFunctionTemplate ft = repostory.getFunctionTemplate(metadat90.CustomPropertyCollection["rfcMame"].Value.ToString());
            if (ft != null)
            {

                JCO.Function function = new JCO.Function(ft);
                List<int> outids = new List<int>();
                List<int> intputids = new List<int>();
                List<int> outdelids = new List<int>();
                List<int> inputdelids = new List<int>();
                #region 添加输出/输入，修改输出/输入
                for (int i = 0; i < function.getTableParameterList().getFieldCount(); i++)
                {
                    foreach (TableType outputype in outputTableType)
                    {
                        #region 输出部分
                        //判断是否需要输出
                        if (outputype.Tablename.Equals(function.getTableParameterList().getName(i)) && outputype.Type.Equals("Pipeline"))
                        {
                            JCO.Table table = function.getTableParameterList().getTable(i);

                            IDTSOutput100 output = null;
                            //查找是否已经存在该输出
                            foreach (IDTSOutput100 outputitem in metadat90.OutputCollection)
                            {
                                if (outputitem.CustomPropertyCollection["SapTableName"] != null
                                    && outputitem.CustomPropertyCollection["SapTableName"].Value.ToString().Equals(function.getTableParameterList().getName(i)))
                                {
                                    output = outputitem;

                                    break;
                                }

                            }
                            if (output == null)
                            {
                                output = metadat90.OutputCollection.New();
                            }
                            output.Name = function.getTableParameterList().getName(i);
                            try
                            {
                                output.Description = function.getTableParameterList().getDescription(i);
                            }
                            catch
                            { }
                            outids.Add(output.ID);//记录要输出的ID  
                            //查找自定义属性是否已经存在
                            IDTSCustomProperty100 sapTableName = null;
                            foreach (IDTSCustomProperty100 sapTableNameitem in output.CustomPropertyCollection)
                            {
                                if (sapTableNameitem.Name.Equals("SapTableName"))
                                {
                                    sapTableName = sapTableNameitem;
                                    break;
                                }
                            }
                            if (sapTableName == null)
                            {
                                sapTableName = output.CustomPropertyCollection.New();
                                sapTableName.Name = "SapTableName";
                            }
                            sapTableName.Value = function.getTableParameterList().getName(i);
                            try
                            {
                                sapTableName.Description = function.getTableParameterList().getDescription(i);
                            }
                            catch
                            { }
                            for (int j = 0; j < table.getFieldCount(); j++)
                            {
                                DataType comDataType = Util.ConventSapTypeToNetType(table.getType(j));
                                //查找输出列是否已经存在
                                IDTSOutputColumn100 column = null;
                                foreach (IDTSOutputColumn100 columnitem in output.OutputColumnCollection)
                                {
                                    if (columnitem.CustomPropertyCollection["SapColumnName"] != null
                                        && columnitem.CustomPropertyCollection["SapColumnName"].Value.ToString().Equals(table.getName(j)))
                                    {
                                        column = columnitem;
                                        break;
                                    }
                                }
                                if (column == null)//如果不存在则添加列
                                {
                                    string Description = "";
                                    try
                                    {
                                        Description = table.getDescription(j);
                                    }
                                    catch { }

                                    AddColumnToOutput(output, table.getName(j), Description, comDataType, (comDataType == DataType.DT_WSTR ? table.getInternalLength(j) : 0), 0, 0);
                                }
                                else//如果存在。则根据条件判断是否要重建现有列
                                {
                                    switch (comDataType)
                                    {
                                        case DataType.DT_WSTR:
                                            if (column.DataType != comDataType || column.Length != table.getInternalLength(j))//如果数据类型不一样，则删除列重建
                                            {
                                                output.OutputColumnCollection.RemoveObjectByID(column.ID);
                                                string Description = "";
                                                try
                                                {
                                                    Description = table.getDescription(j);
                                                }
                                                catch { }
                                                AddColumnToOutput(output, table.getName(j), Description, comDataType, table.getInternalLength(j), 0, 0);
                                            }
                                            break;
                                        default:
                                            if (column.DataType != comDataType)//如果数据类型不一样，则删除列重建
                                            {
                                                output.OutputColumnCollection.RemoveObjectByID(column.ID);
                                                string Description = "";
                                                try
                                                {
                                                    Description = table.getDescription(j);
                                                }
                                                catch { }
                                                AddColumnToOutput(output, table.getName(j), Description, comDataType, 0, 0, 0);
                                            }
                                            break;
                                    }



                                }

                            }
                            break;
                        }
                        #endregion
                    }
                    foreach (TableType inputype in inputTableType)
                    {
                        #region 输入部分
                        if (inputype.Tablename.Equals(function.getTableParameterList().getName(i)) && inputype.Type.Equals("Pipeline"))
                        {
                            JCO.Table table = function.getTableParameterList().getTable(i);

                            IDTSInput100 input = null;
                            //查找是否已经存在该输出
                            foreach (IDTSInput100 inpuputitem in metadat90.InputCollection)
                            {
                                if (inpuputitem.CustomPropertyCollection["SapTableName"] != null
                                    && inpuputitem.CustomPropertyCollection["SapTableName"].Value.ToString().Equals(function.getTableParameterList().getName(i)))
                                {
                                    input = inpuputitem;

                                    break;
                                }

                            }
                            if (input == null)
                            {
                                input = metadat90.InputCollection.New();
                            }
                            //input.HasSideEffects = true; 
                            input.Name = function.getTableParameterList().getName(i);
                            try
                            {
                                input.Description = function.getTableParameterList().getDescription(i);
                            }
                            catch
                            { }
                            intputids.Add(input.ID);//记录要输出的ID  
                            //查找自定义属性是否已经存在
                            IDTSCustomProperty100 sapTableName = null;
                            foreach (IDTSCustomProperty100 sapTableNameitem in input.CustomPropertyCollection)
                            {
                                if (sapTableNameitem.Name.Equals("SapTableName"))
                                {
                                    sapTableName = sapTableNameitem;
                                    break;
                                }
                            }
                            if (sapTableName == null)
                            {
                                sapTableName = input.CustomPropertyCollection.New();
                                sapTableName.Name = "SapTableName";
                            }
                            sapTableName.Value = function.getTableParameterList().getName(i);
                            sapTableName.Description = function.getTableParameterList().getDescription(i);
                            break;
                        }

                        #endregion
                    }

                }
                #endregion
                //记录要删除的ID
                foreach (IDTSOutput100 outpu in metadat90.OutputCollection)
                {
                    int i = 0;
                    foreach (int id in outids)
                    {
                        if (id == outpu.ID)
                        {
                            i++;
                        }

                    }
                    if (i <= 0)
                    {
                        outdelids.Add(outpu.ID);
                    }
                }
                foreach (IDTSInput100 input in metadat90.InputCollection)
                {

                    int i = 0;
                    foreach (int id in intputids)
                    {
                        if (id == input.ID)
                        {
                            i++;
                        }
                    }
                    if (i <= 0)
                    {
                        inputdelids.Add(input.ID);
                    }
                }
                //删除
                foreach (int id in inputdelids)
                {
                    metadat90.InputCollection.RemoveObjectByID(id);
                }
                foreach (int id in outdelids)
                {
                    metadat90.OutputCollection.RemoveObjectByID(id);

                }
            }
            conn.disconnect();

        }


        private static void AddColumnToInput(IDTSInput100 input, string name, string Decsription, DataType type, int length, int Decimals, int Codepage)
        {
            IDTSInputColumn100 column = input.InputColumnCollection.New();


            IDTSCustomProperty100 dataSourceColumnName = column.CustomPropertyCollection.New();
            dataSourceColumnName.Name = "SapColumnName";
            dataSourceColumnName.Value = name;
            dataSourceColumnName.Description = "The name of the column at the Sap source.";

            column.Name = name;
            column.Description = Decsription;
            //column.UsageType= DTSUsageType.  .SetDataTypeProperties(type, length, 0, Decimals, Codepage);
            //IDTSExternalMetadataColumn90 column2 = input.ExternalMetadataColumnCollection.New();

            //column2.Name = column.Name;
            //column2.DataType = column.DataType;
            //column2.Precision = column.Precision;
            //column2.Length = column.Length;
            //column2.Scale = column.Scale;

            //column.ExternalMetadataColumnID = column2.ID;
        }
        private static void AddColumnToOutput(IDTSOutput100 output, string name, string Decsription, DataType type, int length, int Decimals, int Codepage)
        {
            IDTSOutputColumn100 column = output.OutputColumnCollection.New();


            IDTSCustomProperty100 dataSourceColumnName = column.CustomPropertyCollection.New();
            dataSourceColumnName.Name = "SapColumnName";
            dataSourceColumnName.Value = name;
            dataSourceColumnName.Description = "The name of the column at the Sap source.";

            column.Name = name;
            column.Description = Decsription;
            column.SetDataTypeProperties(type, length, 0, Decimals, Codepage);
            IDTSExternalMetadataColumn100 column2 = output.ExternalMetadataColumnCollection.New();

            column2.Name = column.Name;
            column2.DataType = column.DataType;
            column2.Precision = column.Precision;
            column2.Length = column.Length;
            column2.Scale = column.Scale;
            column.ExternalMetadataColumnID = column2.ID;

        }


        #endregion
        #region 运行时
        /// <summary>
        /// 执行之前，建立输出列映射
        /// </summary>
        public override void PreExecute()
        {
            try
            {
                string xml = this.ComponentMetaData.CustomPropertyCollection["PipelineTableValue"] == null ? "" : this.ComponentMetaData.CustomPropertyCollection["PipelineTableValue"].Value.ToString();
                PipelineTableMapings = new List<DataTable>();
                if (!xml.Equals(""))
                {
                    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<DataTable>));
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                    PipelineTableMapings = ser.Deserialize(ms) as List<DataTable>;
                }
                //加载Table的输入配置信息

                if (this.ComponentMetaData.CustomPropertyCollection["ImportTableType"].Value != null)
                {
                    xml = this.ComponentMetaData.CustomPropertyCollection["ImportTableType"].Value.ToString();
                    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<TableType>));
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                    if (ms.Length > 0)
                    {

                        ImportTableType = ser.Deserialize(ms) as List<TableType>;
                    }
                }
            }
            catch (Exception ex)
            {

                this.FireError(ex.Message, true);
            }
        }
        /// <summary>
        /// 处理管道输入,将管道输入转换成SAP Table
        /// </summary>
        /// <param name="inputID"></param>
        /// <param name="buffer"></param>
        public override void ProcessInput(int inputID, PipelineBuffer buffer)
        {
            try
            {
                //this.ComponentMetaData.InputCollection[0].
                IDTSInput100 input90 = this.ComponentMetaData.InputCollection.FindObjectByID(inputID);
                com.sap.mw.jco.IFunctionTemplate ft = this.repostory.getFunctionTemplate(ComponentMetaData.CustomPropertyCollection["rfcMame"].Value.ToString());
                com.sap.mw.jco.JCO.Function function = new com.sap.mw.jco.JCO.Function(ft);
                this.conn.connect();
                string saptablename = input90.CustomPropertyCollection["SapTableName"].Value.ToString();
                com.sap.mw.jco.JCO.Table table = null;
                this.conn.disconnect();

                DataTable TableMaping = new DataTable();
                //找出映射关系
                foreach (DataTable tableitem in PipelineTableMapings)
                {
                    if (tableitem.TableName.Equals(saptablename))
                    {
                        TableMaping = tableitem;
                        break;
                    }
                }

                bool flag = true;
                if (buffer.EndOfRowset)
                {
                    if (this.HashProcessedInputs[saptablename] == null)
                    {
                        this.HashProcessedInputs.Add(saptablename, saptablename);

                    }
                    foreach (TableType tabletype in ImportTableType)
                    {
                        if (tabletype.Type.Equals("Pipeline") && this.HashProcessedInputs[tabletype.Tablename] == null)
                        {
                            flag = false;
                        }
                    }
                }
                else
                {
                    flag = false;
                }
                if (!buffer.EndOfRowset)
                {
                    //判断集合中是否已经存在Table
                    if (this.PipelineInputTables.TryGetValue(saptablename, out table))
                    {
                    }
                    else
                    {
                        table = function.getTableParameterList().getTable(saptablename);
                        PipelineInputTables.Add(saptablename, table);
                    }
                    //判断映射信息是否存在
                    if (TableMaping.Rows.Count > 0)
                    {
                        while (buffer.NextRow())
                        {

                            table.appendRow();
                            //循环输入的列信息
                            foreach (IDTSInputColumn100 column in input90.InputColumnCollection)
                            {

                                //循环列映射信息
                                foreach (DataRow dr in TableMaping.Rows)
                                {
                                    if (System.Convert.ToInt32(dr["OutputId"]) == column.ID)
                                    {
                                        //设置输入Table数据
                                        int colmnindex = this.BufferManager.FindColumnByLineageID(input90.Buffer, column.LineageID);
                                        table.setValue(buffer[colmnindex], dr["InputColumnName"].ToString());
                                        break;
                                    }
                                }
                            }
                        }
                    }

                }
                if (flag)
                {
                    ExecFunction(this.outbuffers);
                }
            }
            catch (Exception ex)
            {

                this.FireError(ex.Message, true);
            }



        }
        /// <summary>
        /// 执行RFC并输出资料
        /// </summary>
        /// <param name="outputs"></param>
        /// <param name="outputIDs"></param>
        /// <param name="buffers"></param>
        public override void PrimeOutput(int outputs, int[] outputIDs, PipelineBuffer[] buffers)
        {
            this.outbuffers = buffers;
            if (this.ComponentMetaData.InputCollection.Count <= 0)
            {
                ExecFunction(buffers);
            }

        }
        /// <summary>
        /// 执行Functin 并输出
        /// </summary>
        /// <param name="buffers"></param>
        private void ExecFunction(PipelineBuffer[] buffers)
        {
            try
            {
                this.FireInformation("Begin Exec!");

                //base.PrimeOutput(outputs, outputIDs, buffers);
                com.sap.mw.jco.IFunctionTemplate ft = this.repostory.getFunctionTemplate(ComponentMetaData.CustomPropertyCollection["rfcMame"].Value.ToString());
                com.sap.mw.jco.JCO.Function function = new com.sap.mw.jco.JCO.Function(ft);
                this.conn.connect();

                List<System.Data.DataTable> pars = new List<System.Data.DataTable>();
                if (this.ComponentMetaData.CustomPropertyCollection["StaticTableValue"].Value != null)
                {
                    string xml = this.ComponentMetaData.CustomPropertyCollection["StaticTableValue"].Value.ToString();
                    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<System.Data.DataTable>));
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                    if (ms.Length > 0)
                    {

                        pars = ser.Deserialize(ms) as List<System.Data.DataTable>;
                    }
                }
                //= ComponentMetaData.CustomPropertyCollection["StaticTableValue"].Value as List<System.Data.DataTable>;


                #region 设置Table
                foreach (TableType tabletype in ImportTableType)
                {
                    if (tabletype.Type.Equals("Static"))//如果是Static，则从固定Table中读取
                    {
                        foreach (System.Data.DataTable tableMaping in pars)
                        {
                            if (tableMaping.TableName.Equals(tabletype.Tablename))
                            {
                                com.sap.mw.jco.JCO.Table table = new com.sap.mw.jco.JCO.Table(function.getTableParameterList().getMetaData(tableMaping.TableName));
                                if (table != null)
                                {
                                    Util.ConventDataTableToSapTable(ref table, tableMaping);
                                    function.getTableParameterList().setValue(table, tableMaping.TableName);
                                }
                                break;
                            }

                        }
                    }
                    else if (tabletype.Type.Equals("Pipeline"))//如果是Pipeline，则从输入管道读取
                    {
                        //if (PipelineInputTables.Count <= 0)
                        //{
                        //    for (int i = 0; i < this.ComponentMetaData.OutputCollection.Count; i++)
                        //    {
                        //        IDTSOutput90 output = this.ComponentMetaData.OutputCollection[i];
                        //        PipelineBuffer buffer = buffers[i];
                        //        buffer.SetEndOfRowset(); 
                        //    }
                        //    return;
                        //}
                        foreach (System.Collections.Generic.KeyValuePair<string, JCO.Table> input in PipelineInputTables)
                        {
                            if (input.Key.Equals(tabletype.Tablename))
                            {
                                //if (input.Value.getRow() <= 0)
                                //{
                                //    for (int i = 0; i < this.ComponentMetaData.OutputCollection.Count; i++)
                                //    {
                                //        IDTSOutput90 output = this.ComponentMetaData.OutputCollection[i];
                                //        PipelineBuffer buffer = buffers[i];
                                //        buffer.SetEndOfRowset();
                                //    }
                                //    return;
                                //}
                                function.getTableParameterList().setValue(input.Value, tabletype.Tablename);
                                break;
                            }
                        }

                    }
                }
                #endregion
                #region 设置输入参数
                List<ParameterValue> imports = new List<ParameterValue>();
                if (this.ComponentMetaData.CustomPropertyCollection["ImportParameterValue"].Value != null)
                {
                    string xml = this.ComponentMetaData.CustomPropertyCollection["ImportParameterValue"].Value.ToString();
                    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<ParameterValue>));
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                    if (ms.Length > 0)
                    {

                        imports = ser.Deserialize(ms) as List<ParameterValue>;
                    }
                }
                foreach (ParameterValue value in imports)
                {
                    if (value.ParameterType.Equals("A"))//简单类型
                    {
                        if (value.ValueType.Equals("Static"))//静态类型
                        {
                            function.getImportParameterList().setValue(value.Value, value.Name);
                        }
                        else//变量类型
                        {
                            if (this.VariableDispenser.Contains(value.Value.Substring(1)))
                            {
                                IDTSVariables100 variable = null;
                                VariableDispenser.LockOneForRead(value.Value.Substring(1), ref variable);
                                function.getImportParameterList().setValue(variable[0].Value, value.Name);
                                VariableDispenser.Reset();
                            }
                        }
                    }
                    else//复杂类型
                    {
                        if (value.StructureValue != null)
                        {
                            JCO.Structure structure = function.getImportParameterList().getStructure(value.Name);
                            for (int i = 0; i < structure.getFieldCount(); i++)
                            {
                                foreach (DataRow dr in value.StructureValue.Rows)
                                {
                                    if (structure.getName(i).Equals(dr["Name"].ToString()))
                                    {
                                        if (dr["Value"].ToString().IndexOf("@") == 0)//变量类型
                                        {
                                            if (this.VariableDispenser.Contains(dr["Value"].ToString().Substring(1)))
                                            {
                                                IDTSVariables100 variable = null;
                                                VariableDispenser.LockOneForRead(dr["Value"].ToString().Substring(1), ref variable);
                                                structure.setValue(variable[0].Value, structure.getName(i));
                                                VariableDispenser.Reset();
                                                break;
                                            }
                                        }
                                        else//静态类型
                                        {
                                            if (dr["Value"].ToString().Equals(null) || dr["Value"].ToString().Equals(""))//确保空值不会被输入
                                            {
                                            }
                                            else
                                            {
                                                structure.setValue(dr["Value"].ToString(), structure.getName(i));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                this.conn.execute(function);
                #region 设置输出参数
                List<ParameterValue> Exports = new List<ParameterValue>();
                if (this.ComponentMetaData.CustomPropertyCollection["ExportParameterValue"].Value != null)
                {
                    string xml = this.ComponentMetaData.CustomPropertyCollection["ExportParameterValue"].Value.ToString();
                    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<ParameterValue>));
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
                    if (ms.Length > 0)
                    {

                        Exports = ser.Deserialize(ms) as List<ParameterValue>;
                    }
                }
                foreach (ParameterValue value in Exports)
                {
                    if (value.ParameterType.Equals("A"))//简单类型
                    {
                        if (!value.Value.Equals("<Null>"))
                        {
                            if (this.VariableDispenser.Contains(value.Value.Substring(1)))
                            {
                                IDTSVariables100 variable = null;
                                VariableDispenser.LockOneForWrite(value.Value.Substring(1), ref variable);
                                variable[0].Value = function.getExportParameterList().getValue(value.Name);
                                VariableDispenser.Reset();
                            }
                        }

                    }
                    else//复杂类型
                    {
                        if (value.StructureValue != null)
                        {
                            JCO.Structure structure = function.getExportParameterList().getStructure(value.Name);
                            for (int i = 0; i < structure.getFieldCount(); i++)
                            {
                                foreach (DataRow dr in value.StructureValue.Rows)
                                {
                                    if (structure.getName(i).Equals(dr["Name"].ToString()))
                                    {

                                        if (this.VariableDispenser.Contains(dr["Value"].ToString().Substring(1)))
                                        {
                                            IDTSVariables100 variable = null;
                                            VariableDispenser.LockOneForWrite(dr["Value"].ToString().Substring(1), ref variable);
                                            variable[0].Value = structure.getValue(dr["Name"].ToString());
                                            VariableDispenser.Reset();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion
                this.FireInformation("End Exec!");
                this.FireInformation("Begin OutPut!");

                for (int i = 0; i < this.ComponentMetaData.OutputCollection.Count; i++)
                {
                    IDTSOutput100 output = this.ComponentMetaData.OutputCollection[i];
                    PipelineBuffer buffer = buffers[i];
                    com.sap.mw.jco.JCO.Table returntable = function.getTableParameterList().getTable(output.CustomPropertyCollection["SapTableName"].Value.ToString());

                    if (returntable.getNumRows() > 0)
                    {
                        do
                        {


                            buffer.AddRow();
                            // List<ColumnInfo> cis = this.columnInformation[output.CustomPropertyCollection["SapTableName"].Value.ToString()];



                            for (int x = 0; x < output.OutputColumnCollection.Count; x++)
                            {


                                if (returntable.getType(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()) == 1)//日期类型特殊处理
                                {
                                    try
                                    {
                                        if (returntable.getValue(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()) != null)
                                        {
                                            buffer[x] = System.Convert.ToDateTime(returntable.getString(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        this.FireError(ex.Message + ". Cannot Convert the Value '" + returntable.getString(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()) + "' to DataTime ");
                                    }
                                }
                                else   if (returntable.getType(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()) == 3)//时间类型特殊处理
                                {
                                    try
                                    {
                                        if (returntable.getValue(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()) != null)
                                        {
                                            buffer[x] = System.Convert.ToDateTime(returntable.getString(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString())).ToString("HHmmss");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        this.FireError(ex.Message + ". Cannot Convert the Value '" + returntable.getString(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString()) + "' to Time ");
                                    }
                                }
                                else
                                {
                                    buffer[x] = returntable.getValue(output.OutputColumnCollection[x].CustomPropertyCollection["SapColumnName"].Value.ToString());
                                }

                            }
                        } while (returntable.nextRow());
                    }
                    buffer.SetEndOfRowset();

                }
                this.FireInformation("End OutPut!");
                this.conn.disconnect();
            }
            catch (Exception ex)
            {

                this.FireError(ex.Message, true);
            }
        }
        #endregion
        #region 输出信息
        public void FireError(string message)
        {
            message = "[" + DateTime.Now.ToString() + "] " + message;
            bool flag = true;
            base.ComponentMetaData.FireError(0x3e8, "SAP", message, "", 0, out flag);
        }

        public void FireError(string message, bool ExceptionToo)
        {
            this.FireError(message);
            throw new Exception(message);
        }

        public void FireInformation(string message)
        {
            message = "[" + DateTime.Now.ToString() + "] " + message;
            bool flag = true;
            base.ComponentMetaData.FireInformation(0x3e8, "SAP", message, "", 0, ref flag);
        }

        public void FireWarning(string message)
        {
            message = "[" + DateTime.Now.ToString() + "] " + message;
            base.ComponentMetaData.FireWarning(0x3e8, "SAP", message, "", 0);
        }
        #endregion
    }
}
